package com.lin.sunnyweather.ui.place

import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.core.view.GravityCompat
import androidx.recyclerview.widget.RecyclerView
import com.lin.sunnyweather.MainActivity
import com.lin.sunnyweather.R
import com.lin.sunnyweather.logic.model.Place
import com.lin.sunnyweather.utils.DataStoreUtils
import kotlinx.android.synthetic.main.activity_main.*
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class LocationAdapter(private val fragment: LocationFragment, private val placeList: List<Place>) :
    RecyclerView.Adapter<LocationAdapter.ViewHolder>() {

    inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
        val placeName: TextView = view.findViewById(R.id.placeName)
        val placeAddress: TextView = view.findViewById(R.id.placeAddress)
    }

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val view =
            LayoutInflater.from(parent.context).inflate(R.layout.location_item, parent, false)
        return ViewHolder(view)
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        val place = placeList[position]
        holder.placeName.text = place.name
        holder.placeAddress.text = place.province
        holder.itemView.setOnClickListener {

            CoroutineScope(Dispatchers.IO).launch {
                DataStoreUtils.setLocationID(place.id)
                DataStoreUtils.setLocationName(place.name)
                withContext(Dispatchers.Main) {
                    val mainActivity = fragment.activity as MainActivity
                    mainActivity.locationID = place.id
                    mainActivity.locationName = place.name
                    mainActivity.refreshWeatherInfo()
                    mainActivity.drawerLayout.closeDrawer(GravityCompat.START)
                }
            }
        }
    }

    override fun getItemCount() = placeList.count()
}